const log4js = require('../../utils/logUtils');
const logger = log4js.getLogger('web');
const constants = require('../../db/constants');
const deviceModel = require('../../model/device');
const channelModel = require('../../model/channel');
const sipServer = require('../../sip/server/server');
const baseController = require('./basectrl');
const deviceCache = require("../../db/deviceCache");

let Device = {

    /**
     * API接口，获取设备列表
     * @param {*} req
     * @param {*} res
     */
    list: async function (req, res) {
        logger.info('通过API接口查询设备列表，参数：', req.query);
        if (!baseController.hasLogin(req, res)) {
            return;
        }
        let page = req.query.page;
        let pagesize = req.query.pagesize;
        let device = req.query.device;

        if (typeof (page) == 'undefined') page = 1;
        if (!pagesize) {
            pagesize = 10000;
        }
        if (typeof (device) == 'undefined') {
            device = null;
        }

        let total = await deviceModel.count(device);
        deviceModel.list(page - 1, pagesize, device).then((items) => {
            let ret = Object.assign(constants.httpCode.OK, {data: {items, total, page, pagesize}});
            res.send(ret);
        });
    },
    /**
     * Query接口读取一个摄像头信息
     * @param {*} req
     * @param {*} res
     */
    query: async function (req, res) {
        if (!baseController.hasLogin(req, res)) {
            return;
        }
        let ret = await deviceModel.getDeviceByDeviceId(req.query.deviceid);

        if (ret.length) {
            let send = Object.assign(constants.httpCode.OK, {data: {items: ret, total: ret.length}});
            res.send(send);
        } else {
            let send = Object.assign(constants.httpCode.NO_DATA, {data: null});
            res.send(send);
        }
    },
    /**
     * 请求目录
     * @param {*} req
     * @param {*} res
     */
    catalog: function (req, res) {
        if (!baseController.hasLogin(req, res)) {
            return;
        }
        let parentId = req.query.parentId;
        sipServer.catalog(parentId).then(() => {
            let ret = Object.assign(constants.httpCode.OK, {data: {}});
            res.send(ret);
        });
    },
    deviceInfo: function (req, res) {
        if (!baseController.hasLogin(req, res)) {
            return;
        }
        let parentId = req.query.parentId;
        sipServer.deviceInfo(parentId).then(() => {
            let ret = Object.assign(constants.httpCode.OK, {data: {}});
            res.send(ret);
        })
    },

    deldevice: function (req, res) {
        if (!baseController.hasLogin(req, res)) {
            return;
        }
        deviceModel.del(req.body.parentId);
        // 删除缓存信息
        if (deviceCache.registry && deviceCache.registry[req.body.parentId]) {
            delete deviceCache.registry[req.body.parentId];
        }
        let ret = Object.assign(constants.httpCode.OK, {data: {}});
        res.send(ret);
    },
    /**
     * 更新通道名称
     * @param {*} req
     * @param {*} res
     */
    updatename: function (req, res) {
        if (!baseController.hasLogin(req, res)) {
            return;
        }
        deviceModel.update({
            deviceid: req.body.deviceid,
            device_name: req.body.device_name
        }).then(() => {
            let ret = Object.assign(constants.httpCode.OK, {data: {}});
            res.send(ret);
        })
    },
    /**
     * 更新
     * @param {*} req
     * @param {*} res
     */
    update: async function (req, res) {
        if (!baseController.hasLogin(req, res)) {
            return;
        }

        let deviceInDb = await deviceModel.getDeviceByDeviceId(req.body.deviceid);
        if (deviceInDb.protocol !== req.body.protocol) {
            // 协议变更，删除原来的子通道信息
            channelModel.deleteByParentId(req.body.deviceid);
        }

        await deviceModel.update({
            deviceid: req.body.deviceid,
            server_id_zlk: req.body.server_id_zlk,
            device_name: req.body.device_name,
            rtsp_url: req.body.rtsp_url,
            protocol: req.body.protocol,
            sumnum: req.body.sumnum
        });

        let channelCount = req.body.sumnum;

        if (req.body.protocol === 'RTSP拉流') {
            if (req.body.rtsp_url) {
                for (let i = 0; i < channelCount; i++) {
                    let rtsp = req.body.rtsp_url.replace('{channel}', (i + 1));
                    channelModel.updateDeviceInfo({
                        DeviceID: (i + 1),
                        ParentID: req.body.deviceid,
                        Name: '',
                        Manufacturer: '',
                        Model: '',
                        Owner: '',
                        CivilCode: '',
                        Address: '',
                        RegisterWay: '',
                        Secrecy: '',
                        rtsp_url: rtsp
                    }).then(() => {

                    });
                }
            }
        } else {
            // 等待国标catalog
        }

        let ret = Object.assign(constants.httpCode.OK, {data: {}});
        res.send(ret);
    }
};

module.exports = Device;
